package com.ruoyi.backend.service.Impl;

import com.ruoyi.backend.constant.InversionConstants;
import com.ruoyi.backend.mapper.FileMapper;
import com.ruoyi.backend.service.FileService;
import com.ruoyi.backend.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private MinioUtil minioUtil;


    @Override
    public boolean deleteFile(String bucketName, String fileName) {
        boolean pgsqlDelete = false;
        if (fileName.isEmpty()) {
            return false;
        }
        Integer status = fileMapper.findFileStatusByName(fileName);
        String pictureName = fileName.substring(0,fileName.length() - 4) + "_thumbnail.png";
        if (status != null && status.equals(InversionConstants.FILE_NOT_DONE)) {
            if (!minioUtil.objectExist(bucketName, fileName) || (minioUtil.removeFile(bucketName, fileName) && minioUtil.removeFile(bucketName,pictureName))) {
                pgsqlDelete = fileMapper.deleteFile(fileName);
            }
        }
        return pgsqlDelete;
    }

    @Override
    public String MINIOUpload(MultipartFile file, String bucketName) {
        //先判断有无桶
        boolean flag = minioUtil.bucketExists(bucketName);
        if (!flag) {
            minioUtil.makeBucket(bucketName);
        }
        //上传文件
        return minioUtil.uploadToBucket(file, bucketName);
    }
}
